<template>
  <div class="app-container">
    <div class="top-main">
    <el-form  class="top-form-fl" :model="param" label-width="auto" :inline="true">
      <el-form-item  label="堆场编号">
        <el-input v-model.trim="param.yardNum" class="uppercase-input" style="width:100%" :placeholder="'请输入堆场编号'" clearable></el-input>
      </el-form-item>
      <el-form-item label="堆场名称">
        <yardSelect :yardName="param.yardName" :selectName="'yardName'" :needInfo="true" @yardId="yardInfoData"
          style="width:100%" :placeholder="'请输入堆场名称'">
        </yardSelect>
      </el-form-item>
      <el-form-item label="创建日期">
        <el-date-picker v-model="param.createTime" type="daterange" range-separator="~" start-placeholder="开始日期"
          end-placeholder="结束日期" clearable/>
      </el-form-item>
      <el-form-item label="经营方">
        <el-input v-model.trim="param.yardCompanyName" style="width:100%" :placeholder="'请输入经营方名称'" clearable></el-input>
      </el-form-item>
    </el-form>
     <div class="top-from-fr">
        <el-button class="top-Search" @click="getTableData" type="primary">搜索</el-button>
        <el-button class="top-Refresh" @click="handleReSet">重置</el-button>
      </div>   
    </div>
    <span style="float: right;">
      <el-tooltip effect="dark" content="此按钮可选择当前页及后续页所有堆场" placement="left">
        <template v-if="isSelectAll">
            <el-button :icon="Finished" size="small" @click="slectAll" plain class="operatingArea">全选</el-button>
        </template>
        <template v-else>
            <el-button size="small" @click="deselectAll" plain class="operatingArea">取消全选</el-button>
        </template>
      </el-tooltip>
      <el-button @click="exportYard" :icon="UploadFilled" size="small" plain>导出</el-button>&nbsp;
      <a :href="downUrl"><el-button :icon="Download" size="small" plain>下载模板</el-button></a>&nbsp;
      <el-button @click="handleUpload" :icon="UploadFilled" size="small" plain>批量导入</el-button>
      <el-button :icon="Plus" type="primary" size="small" @click="dialogAddYard" plain>添加</el-button>
    </span>
    <Table ref="tableRef" v-bind="table" :allId="allId" :isAllCheck="isAllCheck" style="width: 100%;" @pageChange="onTablePageChange" @activEdit="activEdit"
      @showInfo="showInfo" @activSwitch="activSwitch" @activeRemark="activeRemark"  @updateSelectAll="updateSelectAll" :disableHeaderCheckbox="disableHeaderCheckbox">
    </Table>

    <!--dialog -->
    <!-- add 添加堆场  -->
    <el-dialog v-model="param.dialogTableVisible" @close="cancel" style="width: 1000px;">
      <span class="_before" style="display: block; margin-bottom: 20px;padding-bottom: 15px; border-bottom: 1px solid #ccc;">添加堆场</span>
      <el-form ref="addFormRef" :inline="true" :model="addForm" :rules="validationRules.yardRrules" :label-position="'right'" label-width="auto" class="form-inline">
        <el-form-item label="堆场名称" prop="yardName" >
          <div class="line-content">
            <el-input v-model="addForm.yardName" clearable class="div-diy" placeholder="请输入" />
          </div>
        </el-form-item>
        <el-form-item label="所在城市" prop="yardCity" >
          <div class="line-content">
            <citySelect ref="citySelectRef" v-model="addForm.yardCity" :selectCity="addForm.yardCity" class="div-diy" :needInfo="true" @cityId="yardCityId" />
          </div>
        </el-form-item>
        <el-form-item label="经营方" prop="yardCompanyName" >
          <div class="line-content">
            <el-input v-model.trim="addForm.yardCompanyName" clearable class="div-diy" placeholder="请输入" />
          </div>
        </el-form-item>
        <el-form-item label="堆场地址" prop="yardAddress" >
          <div class="line-content">
            <el-input v-model.trim="addForm.yardAddress" clearable class="div-diy" placeholder="请输入" />
          </div>
        </el-form-item>
        <el-form-item label="堆场作业时间" prop="workTime" >
          <div class="line-content">
            <el-input v-model.trim="addForm.workTime" clearable class="div-diy" placeholder="请输入" />
          </div>
        </el-form-item>
        <el-form-item label="国家" prop="yardCityInfo.countryCName">
          <div class="line-content">
            <el-input v-model.trim="addForm.yardCityInfo.countryCName" clearable class="div-diy" disabled placeholder="请输入" />
          </div>
        </el-form-item>
        <el-form-item label="附件" prop="fileList" >
          <div class="line-content" style="width: 100%;">
            <UploadFilesImages ref="attachmentRef" :urlList="param.urlList" :limit="10" :fileSize="10" :type="'jpg/png/jpeg'"></UploadFilesImages>
          </div>
        </el-form-item>
        <el-form-item label="备注" prop="remark" style="width: 100%;">
          <el-input v-model.trim="addForm.remark" type="textarea" show-word-limit clearable placeholder="请输入备注内容" />
        </el-form-item>

        <contactTelEmail ref="contactTelEmailRef" v-if="param.dialogTableVisible"></contactTelEmail>
    
        <el-form-item>
          <el-row class="marginTop20">
            <el-col :span="24" style="font-size: 14px;font-weight: 600;">堆存费信息</el-col>
            <el-col :span="24" style="color: #f59127">*请您务必填写堆存费信息，否则系统无法生成堆存费账单</el-col>
          </el-row>
        </el-form-item>
        <el-table :data="tableData" style="width: 100%" >
          <el-table-column prop="boxType" label="箱型" align="center" width="130">
            <template #default="scope">
              <el-select v-model="scope.row.boxType" disabled>
                <el-option value="5" label="20GP/HQ"></el-option>
                <el-option value="10" label="40GP/HQ"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="boxState" label="箱状态"  align="center">
            <template #default="scope">
              <el-select v-model="scope.row.boxState" disabled>
                <el-option value="5" label="空箱"></el-option>
                <el-option value="10" label="重箱"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="currency" label="结算币种" align="center">
            <template #default="scope">
              <el-select v-model="scope.row.currency">
                <el-option label="$" value="USD" />
                <el-option label="￥" value="CNY"/>
              </el-select>
            </template>
          </el-table-column>
        
          <el-table-column prop="overdueFeeDay" label="超期1天后(箱/天)" width="160" align="center">
            <template #default="scope">
              <el-input v-model.trim="scope.row.overdueFeeDay"  placeholder="请输入"  oninput="value = value.replace(/[^\d.]/g, '').replace(/(\.\d*)\./g, '$1').replace(/^(\d{5})\d+/, '$1').replace(/\.(\d{2})\d+/, '.$1')">
                <template #prefix>
                  <span>{{ { USD: '$', CNY: '￥' }[scope.row.currency] }}</span>
                </template>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column prop="freeStorage" label="免堆期" align="center">
            <template #default="scope">
              <el-input v-model.trim="scope.row.freeStorage" placeholder="请输入" oninput="value = value.replace(/[^\d]/g, '').replace(/^0+/, '')">
                <template #suffix>天
                  <!-- <span>{{ { USD: '$', CNY: '￥' }[scope.row.currency] }}</span> -->
                </template>
              </el-input> 
            </template>
          </el-table-column>
          
          <el-table-column prop="liftingFee" label="吊装费" align="center">
            <template #default="scope">
              <el-input v-model.trim="scope.row.liftingFee"  placeholder="请输入" :formatter="formatterNumber" :parser="formatterNumber">
                <template #prefix>
                  <span>{{ { USD: '$', CNY: '￥' }[scope.row.currency] }}</span>
                </template>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column prop="fallBoxFee" label="倒箱费"  align="center">
            <template #default="scope">
              <el-input v-model.trim="scope.row.fallBoxFee" placeholder="请输入" :formatter="formatterNumber" :parser="formatterNumber">
                <template #prefix>
                  <span>{{ { USD: '$', CNY: '￥' }[scope.row.currency] }}</span>
                </template>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column prop="otherFee" label="其它费用"  align="center">
            <template #default="scope">
              <el-input v-model.trim="scope.row.otherFee" placeholder="请输入" :formatter="formatterNumber" :parser="formatterNumber">
                <template #prefix>
                  <span>{{ { USD: '$', CNY: '￥' }[scope.row.currency] }}</span>
                </template>
              </el-input>
            </template>
          </el-table-column>
        </el-table>

        
        <el-row justify="end" class="marginTop20">
          <el-col :span="4"><el-button :icon="RefreshRight" @click="resetData(1)">重置</el-button></el-col>
          <el-col :span="2"><el-button type="primary" @click="handleAdd">确认</el-button></el-col>
        </el-row>
      </el-form>
    </el-dialog>

    <!-- edit 编辑堆场 -->
    <el-dialog v-model="param.dialogEditVisible" style="width: 1000px;">
      <span class="_before" style="display: block; margin-bottom: 20px;padding-bottom: 15px; border-bottom: 1px solid #ccc;">编辑堆场</span>
      <el-form ref="editYardFrom" :inline="true" :model="param.editInfo" :label-position="'right'" :rules="validationRules.yardRrules"  label-width="auto" class="form-inline">
        <el-form-item label="堆场编号" prop="yardNum">
          <div class="line-content">
            {{ param.editInfo.yardNum }}
          </div>
        </el-form-item>
        <el-form-item label="堆场名称" prop="yardName">
          <div class="line-content">
              <el-input v-model.trim="param.editInfo.yardName"  placeholder="请输入" />
          </div>
        </el-form-item>
        <el-form-item label="所在城市" prop="cityName" >
          <div class="line-content">
            {{ param.editInfo.cityName }}
          </div>
        </el-form-item>
        <el-form-item label="经营方" prop="yardCompanyName" >
          <div class="line-content">
            <el-input v-model.trim="param.editInfo.yardCompanyName"  placeholder="请输入" />
          </div>
        </el-form-item>
        <el-form-item label="堆场地址" prop="yardAddress" >
          <div class="line-content">
            <el-input v-model.trim="param.editInfo.yardAddress"  placeholder="请输入" />
          </div>
        </el-form-item>
        <el-form-item label="堆场作业时间" prop="workTime" >
          <div class="line-content">
            <el-input v-model.trim="param.editInfo.workTime"  placeholder="请输入" />
          </div>
        </el-form-item>
        <el-form-item label="国家" prop="countryName" >
          <div class="line-content">
            {{ param.editInfo.countryName }}
          </div>
        </el-form-item>
        <el-form-item label="状态" prop="status" >
          <div class="line-content">
            {{ { 5: '停用', 10: '堆存中', 15: '未堆存' }[param.editInfo.status] }}
          </div>
        </el-form-item>
        <el-form-item label="当前库存" prop="nowInventory" >
          <div class="line-content">
            {{ param.editInfo.nowInventory }}
          </div>
        </el-form-item>
        <el-form-item label="预配库存" prop="allocationInventory" >
          <div class="line-content">
            {{ param.editInfo.allocationInventory }}
          </div>
        </el-form-item>
        <el-form-item label="可用库存" prop="inventory" >
          <div class="line-content">
            {{ param.editInfo.inventory }}
          </div>
        </el-form-item>
        <el-form-item label="在途箱量" prop="onRouteBox" >
          <div class="line-content">
            {{ param.editInfo.onRouteBox }}
          </div>
        </el-form-item>
        <el-form-item label="总箱量" prop="totalBox" >
          <div class="line-content">
            {{ param.editInfo.totalBox }}
          </div>
        </el-form-item>
        <el-form-item label="附件" prop="fileList" >
          <div class="line-content" style="width: 800px;" v-if="param.dialogEditVisible">
            <UploadFilesImages ref="attachmentRef1" :urlList="param.urlList" :limit="10" :fileSize="10" :type="'jpg/png/jpeg/pdf'"></UploadFilesImages>
          </div>
        </el-form-item>
        <el-form-item label="备注" prop="remark" >
          <div class="line-content" style="width: 800px;">
            <el-input v-model.trim="param.editInfo.remark" :rows="3" type="textarea" show-word-limit placeholder="请输入备注信息"/>
          </div>
        </el-form-item>
      </el-form>

      <contactTelEmail ref="contactTelEmailUpdateRef" :yardContacts="param.editInfo.yardContacts"></contactTelEmail>
      <el-table :data="param.storageFeeInfo"  style="width: 100%" class="marginTop20" >
        <el-table-column prop="boxType" label="箱型" width="130" align="center">
          <template #default="scope">
            <span v-if="scope.row.boxType==5">20GP/HQ</span>
            <span v-if="scope.row.boxType==10">40GP/HQ</span>
          </template>
        </el-table-column>
        <el-table-column prop="boxState" label="箱状态" align="center">
          <template #default="scope">
            <span v-if="scope.row.boxType==5">空箱</span>
            <span v-if="scope.row.boxType==10">重箱</span>
          </template>
        </el-table-column>
        <el-table-column prop="currency" label="结算币种" align="center">
          <template #default="scope">
            <el-select v-model="scope.row.currency">
              <el-option value="USD" label="$"></el-option>
              <el-option value="CNY" label="￥"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="overdueFeeDay" label="超期1天后（箱/天）" align="center"  width="160">
          <template #default="scope">
              <el-input v-model.trim="scope.row.overdueFeeDay"  placeholder="请输入"  oninput="value = value.replace(/[^\d.]/g, '').replace(/(\.\d*)\./g, '$1').replace(/^(\d{5})\d+/, '$1').replace(/\.(\d{2})\d+/, '.$1')">
                <template #prefix>
                <span>{{ { USD: '$', CNY: '￥' }[scope.row.currency] }}</span>
               </template>
              </el-input>
            </template>
        </el-table-column>
        <el-table-column prop="freeStorage" label="免堆期" align="center">
          <template #default="scope">
            <el-input v-model.trim="scope.row.freeStorage"  placeholder="请输入" oninput="value = value.replace(/[^\d]/g, '').replace(/^0+/, '')">
              <template #suffix>天
                <!-- <span>{{ { USD: '$', CNY: '￥' }[scope.row.currency] }}</span> -->
              </template>
            </el-input>
          </template>
        </el-table-column>
        
       
        <el-table-column prop="liftingFee" label="吊装费" align="center">
          <template #default="scope">
            <el-input v-model.trim="scope.row.liftingFee" placeholder="请输入" :formatter="formatterNumber" :parser="formatterNumber">
              <template #prefix>
                <span>{{ { USD: '$', CNY: '￥' }[scope.row.currency] }}</span>
              </template>
            </el-input>
          </template>
        </el-table-column>
        <el-table-column prop="fallBoxFee" label="倒箱费" align="center">
          <template #default="scope">
            <el-input v-model.trim="scope.row.fallBoxFee" placeholder="请输入" :formatter="formatterNumber" :parser="formatterNumber">
              <template #prefix>
                <span>{{ { USD: '$', CNY: '￥' }[scope.row.currency] }}</span>
              </template>
            </el-input>
          </template>
        </el-table-column>
        <el-table-column prop="otherFee" label="其它费用" align="center">
          <template #default="scope">
            <el-input v-model.trim="scope.row.otherFee" placeholder="请输入" :formatter="formatterNumber" :parser="formatterNumber">
              <template #prefix>
                <span>{{ { USD: '$', CNY: '￥' }[scope.row.currency] }}</span>
              </template>
            </el-input>
          </template>
        </el-table-column>
      </el-table>
      <el-row justify="end" class="marginTop20">
        <!-- <el-col :span="3"><el-button type="info"  @click="resetData(2)">重置</el-button></el-col> -->
        <el-col :span="2"><el-button type="primary"  @click="handleEdit">保存</el-button></el-col>
      </el-row>
    </el-dialog>

    <!-- 堆场详情 -->
    <el-dialog v-model="param.dialogInfoVisible" style="width:1000px;">
      <!-- {{param.yardInfo}} -->
      <yardDetail :yardInfo="param.yardInfo"></yardDetail>
    </el-dialog>
    <!-- upload -->
    <el-dialog v-model="param.dialogPitchUploadVisible" style="width: 400px;">
      <span class="_before marginBottom10" style="display: block;">堆场导入</span>
      <uploadFile ref="uploadFileRef" :type="'xls/xlsx'" :displayType="1" :purpose="'import'" :use="'yard'" :drag="true" @uploadSuccess="uploadSuccess" @excelUploadError="excelUploadError"></uploadFile>
    </el-dialog>
    <el-dialog v-model="dialogExcelUploadError"> <!--导入时信息提示-->
        <template v-if="errorType == 'E0001'" >
          <span class="_before">错误提示</span>
          <div style="margin: 20px 0;">异常数据<span style="color: #f59127;">{{dialogExcelUploadErrordInfo.length || "--"}}</span>条，下面是有异常的信息，请您修改后重新导入</div>
          <el-table :data="dialogExcelUploadErrordInfo" border style="width: 100%">
              <el-table-column prop="rowNum" label="异常位置" align="center"  width="200">
                <template #default="scope">第{{scope.row.rowNum}}行</template>
              </el-table-column>
              <el-table-column prop="errorMsg" label="异常原因" align="center" />
          </el-table>
        </template>
        <template v-else-if="errorType == 'B0001'">
          <span class="_before">错误提示</span>
          <div style="margin: 20px 0;text-align: center;">{{dialogExcelUploadErrordInfo}}</div>
        </template>
        <template v-else>
          <span class="_before">成功提示</span>
          <div style="margin: 20px 0;text-align: center;">{{dialogExcelUploadErrordInfo}}</div>
        </template>

        <el-row justify="center" class="marginTop20">
          <el-col :span="3" class="text-center"> <el-button type="primary" @click="dialogExcelUploadError=false">确定</el-button></el-col>
        </el-row>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import contactTelEmail from '@/views/components/contactTelEmail.vue';
import { getCurrentInstance, onActivated, onMounted, reactive, ref } from 'vue';
import Table from '@/components/table'
import yardDetail from '@/views/components/boxYard/yardDetail.vue'
import yardSelect from '@/components/citySelect/yardSelect.vue';
import citySelect from '@/components/citySelect'
import { getTable, addYard, updateYard, getYardInfo, startYard, stopYard ,exportBoxEastYard} from '@/api/boxManage/yard'
// import uploadFile from '@/components/upload/index.vue'
import uploadFile from '@/components/upload/uploadFiles-Images'
import UploadFilesImages from '@/components/upload/uploadFiles-Images'
import { Plus, Edit, Message, Search, Download, Upload, Refresh, UploadFilled,RefreshRight } from '@element-plus/icons-vue'
import { ElMessage,ElMessageBox } from 'element-plus';
import { downloadFile } from '@/utils/download'
import validationRules from '@/directive/rulers'

const table = reactive({
  // 列表数据（必传） 
  data: [],
  // 表头内容（必传，注意格式）
  header: [
    { key: 'yardNum', colWidth: '150', title: '堆场编号', type: '<a>', command: 'showInfo', isCheck: true },
    { key: 'yardName', colWidth: '150', title: '堆场名称', type: 'text', isCheck: true },
    { key: 'yardCompanyName', colWidth: '150', title: '经营方', type: 'text', isCheck: true },
    { key: 'yardAddress', colWidth: '150', title: '堆场地址', type: 'text', isCheck: true },
    { key: 'nowInventory', colWidth: '120', title: '当前库存', type: 'number', isTooltip: true, tooltip: "当前库存=预配库存+可用库存", isCheck: true },
    { key: 'allocationInventory', colWidth: '120', title: '预配库存', type: 'number', isTooltip: true, tooltip: "预配库存=堆场所有提箱单占用锁定的库存之和", isCheck: true },
    {
      key: 'inventory', colWidth: '120', title: '可用库存', type: 'number', isTooltip: true, tooltip: "可用库存=堆场堆存的【已还】集装箱数量-该堆场【已发放】提箱单的所有集装箱数量", isCheck: true
    },
    { key: 'onRouteBox', colWidth: '120', title: '在途箱量', type: 'number', isTooltip: true, tooltip: "在途箱量=堆场所有还箱单预还箱量之和", isCheck: true },
    { key: 'totalBox', colWidth: '100', title: '总箱量', type: 'number', isTooltip: true, tooltip: "总箱量=当前库存+在途箱量", isCheck: true },
    { key: 'status', colWidth: '100', title: '状态', type: 'filter', filter: { 5: '停用', 10: '已堆存', 15: '未堆存' }, cFilter: { 15: '#2158F3', 10: '#22A86D', 5: '#ff0000 ' }, isCheck: true },
    { key: 'createTime', colWidth: '150', title: '创建日期', type: 'dateTime', isCheck: true },
    {
      key: 'operate',
      title: '操作',
      type: 'operate',
      isCheck: true,
      colWidth: '200',
      fixed: 'right',
      buttons: [
        {
          // icon: 'Edit',
          command: 'activEdit',
          name:'编辑'
          // content: '编辑',
         
        },
        {
          isSwitch: true,
          key: 'switchIsOpen',
          command: 'activSwitch',
          content: '启用 / 停用',
          // name: '启用 / 停用',
          isShow: (row: any) => {
            return row.status == 10
          }
        },
      ],
    },
  ],
  // table配置项（必传）
  config: {
    isSelection: true,
    isList: false,
    isPagination: true, // 是否分页
    total: 0, // 分页总数
    loading: false
  },
});

const param = reactive({
  dialogInfoVisible: false,
  dialogEditVisible: false,
  dialogTableVisible: false,
  createTime: '',
  yardName: '',
  yardNum: '',
  tel: '',
  yardCompanyName:'',
  pageNum: 1,
  pageSize: 10,
  yardInfo: {},
  editInfo: {},
  dialogVisibleRemark: false,
  storageFeeInfo:[//堆存费相关信息
    {boxType:5,boxState:5,overdueFeeDay:1,currency:'USD',freeStorage:'0',liftingFee:'0',fallBoxFee:'0',otherFee:'0'},
    {boxType:10,boxState:5,overdueFeeDay:1,currency:'USD',freeStorage:'0',liftingFee:'0',fallBoxFee:'0',otherFee:'0'}
  ],
  dialogPitchUploadVisible:false,
  urlList:[] 
});

const downUrl = ref(import.meta.env.VITE_APP_DOWN_URL + 'default/template/%E6%88%91%E7%9A%84%E5%A0%86%E5%9C%BA%E5%AF%BC%E5%85%A5%E6%A8%A1%E7%89%88.xlsx');
const editForm = reactive({
  id: "",
  contacts: "",
  workTime: [],
  tel: "",
});

const addForm = reactive({
  id: "",
  contacts: "",
  tel: "",
  yardCityInfo: {},
  yardNum:'',
  yardName:'',
  yardAddress:'',
  yardCity: '',
  workTime: '',
  yardCompanyName:'',
  remark:''
});

    // #  * 集装箱箱型：5 - 40HQ   10 - 40GP  15 - 20HQ   20 - 20GP

const tableData = ref([])

onMounted(()=>{
  console.log('444')
  tableData.value = []
  let tableArr = [
    {boxType:'5',boxState:'5',overdueFeeDay:1,currency:'USD',freeStorage:'0',liftingFee:'0',fallBoxFee:'0',otherFee:'0'},
    {boxType:'10',boxState:'5',overdueFeeDay:1,currency:'USD',freeStorage:'0',liftingFee:'0',fallBoxFee:'0',otherFee:'0'}
  ]
  tableData.value.push(...tableArr)
  getTableData();
  param.dialogInfoVisible = false
})

//初始化
function getTableData() {
  let data = {
    pageNum: param.pageNum,
    pageSize: param.pageSize,
    yardName: param.yardName || null,
    yardNum: param.yardNum?.toUpperCase() || null,
    yardCompanyName: param.yardCompanyName || null
  };
  if (param.createTime) {
    data.beginCreateDate = param.createTime[0]
    data.endCreateDate = param.createTime[1]
  }
  table.config.loading = true;
  // 获取列表数据
  getTable(data).then(res => {
    if(res && res.code == '00000' ){
      table.data = res.data.list;
      table.data.map((item: any) => {
        item.switchIsOpen = item.status == 5 ? false : true;
        item.nowInventory = item.inventory + item.allocationInventory // 当前库存 = 预配库存 + 当前库存 
        item.totalBox = item.nowInventory + item.onRouteBox // 总箱量 = 当前库存 + 在途箱量
      });
      table.config.total = res.data.total;
    }
   
  });
  table.config.loading = false;
}

//批量导入
const uploadFileRef = ref({ clearFiles: () => { } });

const handleUpload = () => {
  param.dialogPitchUploadVisible = true
  uploadFileRef.value.clearFiles()
};
const tableRef = ref({ multipleSelection: [] })
// 导出
const exportYard = () =>{ 
  let checkAllItem = []
  if(isSelectAll.value){
    checkAllItem = tableRef.value.multipleSelection
  }else{
    checkAllItem = allId.value
  }
  const ids = checkAllItem.map((item: any) => item.id)
    if (ids.length < 1) return ElMessage.warning('请选择要导出的堆场！')
    ElMessageBox.confirm('确认收取选中的堆场？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        exportBoxEastYard({boxEastYardIds:ids}).then((res: any) => {
            downloadFile(res, '堆场信息')
            ElMessage.success('导出成功！')
        }).catch((error) => {
            ElMessage.error(error)
        })
    }).catch(() => {
        // ElMessage.warning('请选择要收取的箱号！')
    })
}

//分页
function onTablePageChange(page: { pageNum: number; pageSize: number }) {
  param.pageNum = page.pageNum;
  param.pageSize = page.pageSize;
  getTableData();
};

//详情
const showInfo = async(row: any) => {
  await getYardInfo(row.id).then((res: any) => {
    if(res.code == "00000" && res.data?.priceList){
      row.priceList = res.data.priceList
    }else{
      row.priceList = []
    }
  });
  param.yardInfo = row
  param.dialogInfoVisible = true;
};

//打开新增堆场弹窗
const dialogAddYard = () => { 

  tableData.value = []
  let tableArr = [
    {boxType:'5',boxState:'5',overdueFeeDay:1,currency:'USD',freeStorage:'0',liftingFee:'0',fallBoxFee:'0',otherFee:'0'},
    {boxType:'10',boxState:'5',overdueFeeDay:1,currency:'USD',freeStorage:'0',liftingFee:'0',fallBoxFee:'0',otherFee:'0'}
  ]
  tableData.value.push(...tableArr)
  param.dialogTableVisible = true 
};
//add
const { proxy } = getCurrentInstance();
const contactTelEmailRef = ref();
const attachmentRef = ref()
const handleAdd = () => {
  const validResult = contactTelEmailRef.value.validResult()
  
  if (!validResult) return
  proxy.$refs.addFormRef.validate(valid => {
    if (!valid) return
    const cityInfo = addForm.yardCityInfo
    const contactList = contactTelEmailRef.value.getContactList() || []
    if (contactList.length == 0) return ElMessage.warning('请添加联系人')
    let fileList = attachmentRef.value.fileList || []
    const data = {
      yardName: addForm.yardName,
      cityName: cityInfo.cityCName,
      cityId: cityInfo.id,
      countryId: cityInfo.countryId,
      countryName: cityInfo.countryCName,

      yardCompanyName:addForm.yardCompanyName,
      yardAddress: addForm.yardAddress,
      workTime: addForm.workTime,

      fileList: JSON.stringify(fileList),
      remark: addForm.remark,
      yardContacts: JSON.stringify(contactList), //[{\"contacts\":\"联系人1\",\"areaCode\":\"区号\",\"tel\":\"电话\",\"email\":\"邮箱\"}]
      priceList:  tableData.value
      
    }
    addYard(data).then((res: any) => {
      cancel()
      getTableData();
      param.dialogTableVisible = false
    });
  })
};
const citySelectRef = ref();
const attachmentRef1 = ref()
const addFormRef=ref()
//关闭弹框
const cancel = () => {
  addFormRef.value.resetFields()// 重置数据
  addForm.id = ""
  addForm.contacts = ""
  addForm.tel = ""
  addForm.yardCityInfo = {}
  addForm.yardNum = ''
  addForm.yardName = ''
  addForm.yardAddress = ''
  addForm.yardCity = ''
  addForm.workTime = ''
  addForm.yardCompanyName = ''
  addForm.remark = ''
  param.urlList = []
  param.dialogTableVisible = false 
}

const resetData = (val:number) => {
  if(val==1){
    addForm.yardName = ''
    addForm.yardCity = ''
    addForm.yardCityInfo = {}
    addForm.yardCompanyName = ''
    addForm.yardAddress = ''
    addForm.workTime = ''
    addForm.remark = ''
    // 重置超期费信息
   tableData.value = []
    let tableArr = [
      {boxType:"5",boxState:"5",overdueFeeDay:1,currency:'$',freeStorage:'',liftingFee:'',fallBoxFee:'',otherFee:''},
      {boxType:"10",boxState:"5",overdueFeeDay:1,currency:'￥',freeStorage:'',liftingFee:'',fallBoxFee:'',otherFee:''}
    ]
    tableData.value.push(...tableArr)
    citySelectRef.value.clearSelectCity()
    attachmentRef.value.clearFiles();
    contactTelEmailRef.value.resetAll()
  }else if(val==2){
    param.storageFeeInfo = [
      {boxType:5,boxState:5,overdueFeeDay:1,currency:'USD',freeStorage:'0',liftingFee:'0',fallBoxFee:'0',otherFee:'0'},
      {boxType:10,boxState:5,overdueFeeDay:1,currency:'USD',freeStorage:'0',liftingFee:'0',fallBoxFee:'0',otherFee:'0'}
      ]
    attachmentRef1.value.clearFiles()
    contactTelEmailUpdateRef.value.resetAll()
  }

   
  //重置联系人信息
  
  ElMessage.success('重置成功');
}
//编辑
const activEdit = (row: any) => {
  getYardInfo(row.id).then((res: any) => {
    param.editInfo = res.data
    editForm.tel = row.tel
    editForm.contacts = row.contacts
    editForm.workTime = row.workTime
    param.editInfo.nowInventory = row.inventory + row.allocationInventory // 当前库存 = 预配库存 + 当前库存 
    param.editInfo.totalBox = row.nowInventory + row.onRouteBox // 总箱量 = 当前库存 + 在途箱量
    if(res.data.fileList==null){
      param.urlList = []

    }else{
      param.urlList = JSON.parse(res.data.fileList) || []

    }
  
    if(res.data.priceList.length){
      param.storageFeeInfo = res.data.priceList
    }else{
      param.storageFeeInfo = [
      {boxType:5,boxState:5,overdueFeeDay:1,currency:'USD',freeStorage:'0',liftingFee:'0',fallBoxFee:'0',otherFee:'0'},
      {boxType:10,boxState:5,overdueFeeDay:1,currency:'USD',freeStorage:'0',liftingFee:'0',fallBoxFee:'0',otherFee:'0'}
      ]
    }
    
    param.dialogEditVisible = true;
  });

};
const contactTelEmailUpdateRef = ref();
const editYardFrom  = ref()
const handleEdit = async () => {
    const validResult = await contactTelEmailUpdateRef.value.validResult()
    if (!validResult) return
    const contactList = contactTelEmailUpdateRef.value.getContactList() || []
    
    if (contactList.length == 0) return ElMessage.warning('请添加联系人')
    let fileList = attachmentRef1.value.fileList || []
    proxy.$refs.editYardFrom.validate(valid => { 
      if (!valid) return ElMessage.warning('请填写必填项！')
      const data = {
        id: param.editInfo.id,
        yardName: param.editInfo.yardName,
        yardCompanyName: param.editInfo.yardCompanyName,
        yardAddress: param.editInfo.yardAddress,
        yardContacts: JSON.stringify(contactList),
        workTime: param.editInfo.workTime,
        priceList: param.storageFeeInfo,
        remark:  param.editInfo.remark,
        fileList: JSON.stringify(fileList)

      }
      updateYard(data).then((res: any) => {
        // console.log(res.data)
        getTableData();
        param.dialogEditVisible = false;
      }).catch((error) => {
        console.log("ERROR",error)
        // ElMessage.warning()
      });
  })
};

//关闭
const activSwitch = (row: any) => {

  if (row.switchIsOpen) {
    startYard(row.id).then((res: any) => {
      getTableData();
    });
  } else {
    stopYard(row.id).then((res: any) => {
      getTableData();
    });
  }
}

const handleReSet = () => {
  param.yardNum = ''
  param.createTime = '';
  param.yardName = "";
  param.yardCompanyName = '';
  getTableData();
};

//
const yardCityId = (id: string, info: any) => {
  addForm.yardCityInfo = info
  addForm.yardCity = id
}

//
//堆场组件 emit 
const yardInfoData = (id: string, info: any) => {
  if (info) { param.yardName = info.yardName }
}

// 添加修改备注
// const activeRemark = (row: any) => {
//   rowData.value = row;
//   console.log("activeRemark",row)
//   param.remarkValSync = row.remark;
//   param.dialogVisibleRemark = true;
//   if (row.remark) {
//     param.remarksTitle = '编辑备注'
//   } else {
//     param.remarksTitle = '添加备注'
//   }
// };
//添加|修改备注
// const handleRemark = (row: any) => {
  
//   const data = { id: rowData.value.id, "remark": param.remarkValSync }
//   updateContainersMark(data).then((res: any) => {
//     ElMessage.success('备注修改成功');
//     param.dialogVisibleRemark = false;
//     getTableData()
//   })
// };



const dialogExcelUploadError = ref(false)
const dialogExcelUploadErrordInfo = ref()
const errorType = ref()
// 上传堆场失败调用
const excelUploadError = (info:any) =>{
  dialogExcelUploadError.value = true

  if(info.code == "E0001"){
    errorType.value = 'E0001'
    dialogExcelUploadErrordInfo.value = JSON.parse(info.data)
  }else if(info.code == "B0001"){
    errorType.value = 'B0001'
    dialogExcelUploadErrordInfo.value = info.msg
  }else{
    errorType.value = '00000'
    dialogExcelUploadErrordInfo.value = info.data
  }
  uploadFileRef.value?.clearFiles()
}
const formatterNumber = (value:any) =>{ 
  const val = value.replace(/[^\d.]/g, '').replace(/(\.\d*)\./g, '$1').replace(/^(\d{5})\d+/, '$1').replace(/\.(\d{2})\d+/, '.$1')
  if (val.indexOf('.') === -1) {
    return (val- 0)
  }else {
    const valArr = val.split('.')
    return (valArr[0] - 0).toString() + '.' + valArr[1]
  }
}
// 上传堆场成功调用
const uploadSuccess = (result:any) => {
  getTableData();
  param.dialogPitchUploadVisible = false
  ElMessage.success({
    message:"请您及时在已导入堆场信息内及时补录堆存费信息，否则系统无法生成堆存费账单",
    duration: 10000
  }) 
}


const isSelectAll = ref(true) // true:显示全选按钮  false：显示取消全选按钮
const allId = ref([]) // 使用全选功能时使用
const disableHeaderCheckbox = ref(false) // true:禁用表头全选/全取消 选择框 false:开启 表头全选/全取消 选择框
const isAllCheck = ref(false) //是否使用全选功能
const checkAll = ref([]) //点击全选按钮时 选中列表所有内容（包含当前页和所有后续页）
const slectAll = async(val:any) =>{
    checkAll.value = []
    await getTable({ pageNum:1,pageSize:10000}).then(res =>{ 
      if(res.code == "00000" && res.data.list  && res.data.total){
        isSelectAll.value = false
        disableHeaderCheckbox.value = true
        res.data.list.forEach(item => {
          checkAll.value.push(item)
        })
        isAllCheck.value = true
        allId.value = checkAll.value
        tableRef.value.checkAll()
      }else{
        ElMessage.error("全选失败，请刷新页面，或者手动选择")
      }
 })
}
const deselectAll = () =>{
  allId.value = []
  disableHeaderCheckbox.value = false
  tableRef.value.clearCheckAll()
  isSelectAll.value = true
}

const updateSelectAll = (val) => {
  allId.value = val
  // console.log("11111",allId.value)
}
</script>

<style lang="scss" scoped>

.el-form-diy {
  width: 100%;

  .div-diy {
    width: 250px;
  }
}
.currency{
  display: inline-block;
  width: 20%;
}

.form-inline div.line-content {
  width: 180px;
}

/* Vue 3 深度选择器 */
.hide-spin-buttons :deep(input::-webkit-outer-spin-button),
.hide-spin-buttons :deep(input::-webkit-inner-spin-button) {
  -webkit-appearance: none;
  margin: 0;
}

.hide-spin-buttons :deep(input[type="number"]) {
  -moz-appearance: textfield; /* Firefox */
}

</style>